import { loginApi } from '@/api';
import { App, Input, Statistic } from 'antd';
import React, { useMemo } from 'react';
import OStyle from '../index.less';
import type { SendMsmCodeProps } from '../interface';
import AWSC from './AWSC';

const Countdown = Statistic.Countdown;

/**
 * @desc 验证码发送状态
 */
export const SendStatusEnum = {
  /**
   * @desc 未发送
   */
  unSend: 0,

  /**
   * @desc 发送中，和5重复，目前没有用到
   */
  sending: 1,

  /**
   * @desc 发送成功倒计时中
   */
  sended: 2,

  /**
   * @desc 已经成功发送过一次并且倒计时结束
   */
  reSend: 3,

  /**
   * @desc 禁止发送
   */
  noSend: 4,

  /**
   * @desc 发送前接口检查，检查手机号状态
   */
  checkSend: 5,

  /**
   * @desc 需要滑块验证
   */
  awscCheck: 6,
};

//手机号状态
const isGetCodeMoreResponse = {
  /**
   * @desc 当天首次请求,直接通过
   */
  once: 1,

  /**
   * @desc 当天请求两次，需要滑块进行验证
   */
  twice: 2,

  /**
   * @desc 当天请求>=3次
   */
  more: 3,

  /**
   * @desc 手机账号未在平台注册
   */
  noRegistered: 4,
};

const SendMsmCode: React.FC<SendMsmCodeProps> = (props) => {
  const { message } = App.useApp();
  const { mobile, value, onChange, onStatusChange, onErrmsgChange, status } = props;
  const mobileValue = useMemo(() => (mobile ? mobile.replaceAll(' ', '') : ''), [mobile]);

  // 发送验证码接口
  const doSendCode = (data: AWSCModule.NCSuccessData) => {
    loginApi
      .getSMSCode({ mobile: mobileValue, type: 1, ...data })
      .then((res: any) => {
        if (res.code === '200') {
          // 发送验证码成功之后开始倒计时。更新视图显示
          onStatusChange(SendStatusEnum.sended);
          onErrmsgChange({
            type: 'validating',
            text: '短信验证码已发送,请到手机上查收...',
          });
        } else {
          message.error('发送失败！');
          onStatusChange(SendStatusEnum.reSend);
        }
      })
      .catch((err) => {
        console.log('--SendMSMCode--doSendCode--err--:', err);
      });
  };

  // 发送短信验证码
  const sendCode = async () => {
    onErrmsgChange({ type: '', text: '' });

    if (!mobileValue) {
      onErrmsgChange({ type: 'error', text: '请输入手机号码！' });
      return;
    }
    if (!/^(1)\d{10}$/.test(mobileValue)) {
      onErrmsgChange({ type: 'error', text: '手机号码有误，请核验后重试！' });
      return;
    }
    onStatusChange(SendStatusEnum.checkSend);
    try {
      // 手机号是否注册过
      const regRes: any = await loginApi.checkMobileIsRegistered({ mobile: mobileValue });
      console.log('--regRes--:', regRes);
      if (regRes.code === '0') {
        // 当天获取验证码次数
        const moreRes = await loginApi.checkGetCodeMore({ mobile: mobileValue, type: 1 });
        if (moreRes?.data) {
          // >=3;
          onErrmsgChange({ type: 'error', text: '操作太频繁，请稍后重试！' });
          onStatusChange(SendStatusEnum.noSend);
        } else {
          const timesRes = await loginApi.getHasSendedCodeTimes({ mobile: mobileValue });
          if (timesRes?.data) {
            //两次（展示滑块验证）
            onStatusChange(SendStatusEnum.awscCheck);
          } else {
            // 首次
            doSendCode({
              sessionId: '',
              sig: '',
              token: '',
            });
          }
        }
      } else {
        onErrmsgChange?.({ type: 'error', text: '当前手机号暂未注册' });
        onStatusChange(SendStatusEnum.unSend);
      }
    } catch (err) {
      console.log('--SendMSMCode--判断是否要展示滑块--err--:', err);
      onErrmsgChange?.({ type: 'error', text: '获取手机状态报错' });
      onStatusChange(SendStatusEnum.unSend);
    }
  };

  //input后缀--短信验证码按钮
  const inputSufix = useMemo(() => {
    if (status === SendStatusEnum.unSend || status === SendStatusEnum.reSend || status === SendStatusEnum.noSend) {
      return (
        <span className={OStyle.code_suffix_text} onClick={sendCode}>
          {status === SendStatusEnum.unSend ? '获取验证码' : '重新获取'}
        </span>
      );
    } else if (status === SendStatusEnum.checkSend || status === SendStatusEnum.sending) {
      // 5 | 1
      return '发送中';
    } else if (status === SendStatusEnum.sended) {
      return (
        <Countdown
          value={Date.now() + 60000}
          valueStyle={{ fontSize: 14 }}
          format="s"
          onFinish={() => {
            onErrmsgChange({ type: '', text: '' });
            onStatusChange(SendStatusEnum.reSend);
          }}
        />
      );
    }
  }, [status, mobileValue]);

  return status === SendStatusEnum.awscCheck ? (
    <AWSC onSuccess={doSendCode} />
  ) : (
    <Input
      bordered={false}
      size="large"
      placeholder="请输入验证码"
      prefix={
        <div className={OStyle.password_icon}>
          <div></div>
        </div>
      }
      onChange={(e) => {
        let value = e.target.value; //字符串
        value = value.replace(/[^\d]/g, '').substring(0, 4);
        onChange(value);
      }}
      value={value}
      suffix={inputSufix}
      style={{ width: '100%' }}
    ></Input>
  );
};

export default SendMsmCode;
